package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.common.PageExecutingResult;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;

public class ResultTableWidget extends FlexTable {

	private List<String> m_ids;
	private List<StopExecutionEventListener> m_listeners;

	private static final int NAME = 0, TIME = 1, STATE = 2, STOP = 3;

	public ResultTableWidget() {
		m_ids = new LinkedList<String>();
		m_listeners = new LinkedList<StopExecutionEventListener>();
		this.setText(0, NAME, "Page");
		this.setText(0, TIME, "Start Time");
		this.setText(0, STATE, "Progress");
		this.setText(0, STOP, "Stop");
	}

	public void addResult(final PageExecutingResult result) {
		if (m_ids.contains(result.getID()))
			return;

		int currentRow = this.getRowCount();

		setWidget(currentRow, NAME, new Anchor(result.getName(),
				"http://somelink/"));
		setText(currentRow, TIME, result.getStartTime().toString());
		setText(currentRow, STATE, result.getState().name());

		Button stopButton = new Button("x");
		stopButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				notifyListeners(new StopExecutionEvent(result.getID()));
			}

		});
		setWidget(currentRow, STOP, stopButton);
		
		m_ids.add(result.getID());
	}

	public void updateResult(PageExecutingResult result) {
		if (!m_ids.contains(result.getID()))
			return;

		int row = m_ids.indexOf(result.getID()) + 1;
		setText(row, STATE, result.getState().toString());

	}

	public void removeResult(PageExecutingResult result) {
		if(!m_ids.contains(result.getID()))
			return;
		
		int index = m_ids.indexOf(result.getID());
		removeRow(index + 1);
		m_ids.remove(index);
	}

	public void addStopExecutionEventListener(StopExecutionEventListener listener) {
		m_listeners.add(listener);
	}

	public void removeStopExecutionEventListener(StopExecutionEventListener listener) {
		m_listeners.remove(listener);
	}
	
	private void notifyListeners(StopExecutionEvent event){
		for(StopExecutionEventListener l : m_listeners)
			l.actionPerformed(event);
	}

}
